const fs = require('fs');
const request = require('request');
const _ = require('lodash');
const Promise = require('bluebird');
const moment = require('moment');
const useragent = require('useragent');
const signature = require('cookie-signature');
const emoji = require('node-emoji');
const generateSid = function (sid) {
    return 's:' + signature.sign(sid, 'sid');
}

/**
 * @api {post} /api/public/v1/user/send_code 发送验证码
 *
 */
exports.sendCode = function ({body, session}, {models: {Users}, cache: {settings}, sms}) {
    let {tel, type} = body;
    if (!/^1[0-9]{10}$/.test(tel)) {
        return {success: false, message: '请输入正确的手机号码'};
    }
    if (!type || (type != 'forgot' && type != 'register')) {
        return {success: false, message: '获取验证码类型不正确'};
    }
    let codeVal = session[type];
    if (codeVal) {
        if (new Date().getTime() < codeVal.time) {
            return {success: false, message: '请等待60后再重新获取'};
        }
    }
    return Users.findOne({where: {tel: tel}, attributes: ['id']}).then(function (user) {
        let tpl_content, title = settings.value('title'), smsConfig = settings.value('sms');
        if (!smsConfig) {
            return {success: false, message: '配置错误'};
        }
        if (type == 'forgot') {
            if (!user) {
                return {success: false, message: '根据手机号码未找到用户,请检查是否输入错误'};
            }
            tpl_content = smsConfig.tpl_forgot;
        } else if (type == 'register') {
            if (user) {
                return {success: false, message: '手机号码已经存在,一个手机号只能注册一个用户'};
            }
            tpl_content = smsConfig.tpl_register;
        }
        let code = Math.random().toString(10).substr(-6);
        // let form = {
        //     apikey: smsConfig.apikey,
        //     mobile: tel,
        //     text: '【' + title + '】' + tpl_content.replace('#code#', code)
        // }
        let form = {
            u: smsConfig.username,
            p: smsConfig.password,
            m: tel,
            c: tpl_content.replace('#code#', code)
        }
        return sms.sendCode(form).then(function (result) {
            if (result.success) {
                session['code_' + type] = {
                    time: new Date().getTime() + 1000 * 60,
                    expire: new Date().getTime() + 1000 * 60 * 10,
                    code: code,
                    tel: tel
                };
            } else {
                console.error('sms error', result.data);
            }
            return result;
        });
    });
}

/**
 * @api {post} /api/public/v1/user/login?is_admin=[0,1] 登录
 */
exports.login = function ({body, query, session, req}, {models: {Users, LoginLogs}, cache: {settings}}) {
    let {tel, username, password, remember_me} = body, {is_admin} = query;
    if (!tel && username) {
        tel = username;
    }
    if (!tel || !password) {
        return {success: false, message: '参数错误'};
    }
    return Users.loginV2({tel: tel, password: password, is_admin: is_admin}).then(function (result) {
        if (result.success) {
            result.sid = generateSid(session.id);
            if (remember_me) {
                session.cookie.maxAge = 1000 * 60 * 60 * 24 * 30 * 12;
            } else {
                session.cookie.expires = false;
            }

            let user = result.data;
            session.user_id = user.id;
            session.touch();

            //记录登录日志
            LoginLogs.create({
                user_id: user.id,
                sid: session.id,
                ext_data: JSON.stringify({
                    useragent: req.headers['user-agent'],
                    ip: req.header('x-forwarded-for') || ''
                })
            });
        }
        return result;
    });
}

/**
 * @api {post} /api/public/v1/user/forgot 重围密码
 */
exports.forgot = function ({body, session}, {models: {Users, Auths}, redis}) {
    let {tel, code, password} = body;
    if (!/^1[0-9]{10}$/.test(tel)) {
        return {success: false, message: '请输入正确的手机号码'};
    }
    if (!/^[0-9]{6}$/.test(code)) {
        return {success: false, message: '请输入六位数字验证码'};
    }
    let code_forgot = session.code_forgot;
    if (!code_forgot || tel != code_forgot.tel || code != code_forgot.code || new Date().getTime() > code_forgot.expire) {
        return {success: false, message: '验证码错误'};
    }
    return Users.findOne({where: {tel: tel}, attributes: ['id']}).then(function (user) {
        return Auths.forgotV2({user_id: user.id, password: password}).then(function (result) {
            if (result.success) {
                return Users.cleanUserSessionV2({id: user.id, redisClient: redis.globalClient}).then(function () {
                    return result;
                });
            }
            return result;
        });
    });
}

/**
 * @api {post} /api/public/v2/user/register 注册
 */
exports.register = function ({body, session, req}, {models: {Users, LoginLogs}, cache: {settings}, controller, qiniu}) {
    let {tel, code, password, invite_code} = body;
    if (!/^1[0-9]{10}$/.test(tel)) {
        return {success: false, message: '请输入正确的手机号码'};
    }
    if (!/^[0-9]{6}$/.test(code)) {
        return {success: false, message: '请输入六位数字验证码'};
    }
    let code_register = session.code_register;
    if (!code_register || tel != code_register.tel || code != code_register.code || new Date().getTime() > code_register.expire) {
        return {success: false, message: '验证码错误'};
    }

    body = controller.permissions({body: body, model: Users, permission: 'User', include: {password: password}});
    if (!password) {
        return {success: false, message: '密码不能为空'};
    }
    let handle = function () {
        return Users.registerV2(body).then(function (result) {
            if (result.success) {
                result.sid = generateSid(session.id);
                if (body.remember_me) {
                    session.cookie.maxAge = 1000 * 60 * 60 * 24 * 30 * 12;
                } else {
                    session.cookie.expires = false;
                }
                session.user_id = result.data.id;
                session.touch();

                //记录登录日志
                LoginLogs.create({
                    user_id: result.data.id,
                    sid: session.id,
                    ext_data: JSON.stringify({
                        useragent: req.headers['user-agent'],
                        ip: req.header('x-forwarded-for') || ''
                    })
                });
            }
            return result;
        });
    }
    if (invite_code) {
        return Users.findOne({where: {code: invite_code}, attributes: ['id']}).then(function (iuser) {
            if (iuser) {
                body.inviter_id = iuser.id;
            }
            return handle();
        });
    }
    return handle();
}

/**
 * @api {post} /api/public/v1/user/change_password 修改密码
 */
exports.changePassword = function ({body, user_id}, {models: {Users, Auths}, redis}) {
    let {oldpassword, newpassword} = body;
    return Auths.changeV2({
        user_id: user_id,
        oldpassword: oldpassword,
        newpassword: newpassword
    }).then(function (result) {
        if (result.success) {
            return Users.cleanUserSessionV2({id: user_id, redisClient: redis.globalClient}).then(function () {
                return result;
            });
        }
        return result;
    });
}

/**
 * @api {post} /api/public/v1/user/load 加载用户信息
 */
exports.load = function ({user_id}, {models: {Users}}) {
    return Users.findOne({where: {id: user_id}});
}

/**
 * @api {post} /api/public/v1/user/edit 编辑用户
 */
exports.edit = function ({body, user_id}, {models: {Users}, controller}) {
    let where = {id: user_id};
    body = controller.permissions({body: body, model: Users, permission: 'User'});
    delete body.tel;
    return Users.update(body, {where: where}).then(function (result) {
        return {success: (result[0] > 0)};
    });
}

/**
 * @api {post} /api/public/v1/user/edit_by_wechat 通过微信更新
 */
exports.editByWechat = function ({body, user_id}, {models: {Users}, config, wechatInstance, qiniu}) {
    return Users.findOne({where: {id: user_id}}).then(function (user) {
        if (!user || !user.openid) {
            return {success: false};
        }
        return new Promise(function (resolve) {
            wechatInstance.shopWebApi.getUser(user.openid, function (err, result) {
                if (err) {
                    console.error('\n', err.stack || err.message);
                    return resolve({success: false});
                }
                let body = {nickname: emoji.strip(result.nickname || '')};
                qiniu.portraitUpload(config.qiniu, result.headimgurl).then(function (result) {
                    if (result.success) {
                        body.image = result.image;
                    }
                    return Users.update(body, {where: {id: user_id}}).then(function () {
                        return resolve({success: true});
                    });
                });
            });
        });
    });
}

/**
 * @api {post} /api/public/v1/user/validate 验证
 */
exports.validate = function ({body}, {models: {Users}}) {
    let {id, tel} = body;
    let where = {tel: tel};
    if (id) {
        where.id = {ne: id}
    }
    return Users.count({where: where}).then(function (count) {
        return {valid: !(count > 0)};
    });
}

/**
 * @api {post} /api/public/v1/user/logout 退出登录
 */
exports.logout = function ({session}) {
    session.cookie.expires = false;
    session.user_id = 0;
    session.source = '';
    session.openid = '';
    session.unionid = '';
    session.touch();
    return {success: true};
};
